import Taro, { useDidShow, useRouter } from '@tarojs/taro'
import { useReducer, useState } from 'react'
import { View, Text, Swiper, SwiperItem, Button } from '@tarojs/components'
import { AtDivider } from 'taro-ui'

import './index.scss'
import { useReady } from '@tarojs/taro'
import { queryAllChargingOrderApi, querySingleChargingApi } from '../../../services/ChargeLog'
import XLoadingPage from '../../../components/XLoadingPage'
import { hideLoading, reducer, showLoading, showModal, showToast, strategyTypeIsTime } from '../../../utils'
import { queryStopChargeStatusApi, stopChargeApi } from '../../../services/Charge'
import GlobalData from '../../../global'


export default () => {
    let orderId = useRouter().params.orderId
    const ChargeQuEl = (props : {type:StrategyType; quantity:number}) => {
        let hour = 0
        let minute = 0
        let quantity = Number(props.quantity)
        if(strategyTypeIsTime(props.type)) {
            hour = Math.floor(quantity / 3600)
            minute = Math.ceil(quantity % 3600 / 60)
        }

        return <View className='charge-time'>
                {strategyTypeIsTime(props.type)
                ? <>
                    <Text className='number'>{hour}</Text>
                    <Text className='unit'> 小时</Text>
                    <Text className='number'> {minute}</Text>
                    <Text className='unit'> 分钟</Text>
                 </>
                : <>
                    <Text className='number'>{quantity}</Text>
                    <Text className='unit'> 度</Text>
                 </>
                }
            </View>
    }

    let [INIT, setINIT] = useState(false)
    let [loadingData, dispatchLoadingData] = useReducer(reducer, {
        showLoadingPage : true, //是否显示加载页面
        loadingErrMsg : '',
        loadErr : false
    })
    let [currentIndex, setcurrentIndex] = useState(0)
    let [orderList, setorderList] = useState<ChargingOrder[]>([])
    let [queryOrderStatusCount, setqueryOrderStatusCount] = useState(0) //查询充电订单状态次数

    async function queryChargingOrder() {
        if(orderId) {
            querySingleChargingApi(Number(orderId)).then(data => {
                if(data) {
                    setorderList([data])
                    dispatchLoadingData({showLoadingPage : false})
                }else {
                    dispatchLoadingData({loadingErrMsg : '暂无充电订单', loadErr : true})
                }

            })
        }else {
            let rows = await queryAllChargingOrderApi()
            if(rows && rows.length > 0) {
                setorderList(rows)
                dispatchLoadingData({showLoadingPage : false})
            }else {
                dispatchLoadingData({loadingErrMsg : '暂无充电订单', loadErr : true})
            }
        }
    }

    function goAddCharge() {
        let order = orderList[currentIndex]
        GlobalData.lastOrder = order
        Taro.navigateTo({
            url : `/pages/charge/add/index?deviceId=${order.deviceId}&orderId=${order.orderId}`
        })
    }

    function queryStopOrderStatus(orderId:number) { //停止充电之后，查询状态
        setTimeout(async () => {
            queryOrderStatusCount += 1
            setqueryOrderStatusCount(queryOrderStatusCount)
            let res = await queryStopChargeStatusApi(orderId)
            if(res.success) {
                let status = Number(res.data)
                if(status == 0) { //继续查询
                    if(queryOrderStatusCount > 3) {
                        hideLoading()
                        showModal('停止充电失败')
                        return
                    }

                    queryStopOrderStatus(orderId)

                }else if(status == 1) { //停止成功
                    hideLoading()
                    showToast('停止充电成功')
                    GlobalData.chargingCount --

                    let url = '/userClient/pages/chargeLog/detail/index?orderId=' + orderId
                    if(orderList.length == 1) {
                        Taro.redirectTo({url})
                    }else {
                        orderList.splice(currentIndex, 1)
                        Taro.navigateTo({url})
                    }
                }else if(status == 2) { //停止失败
                    hideLoading()
                    showModal('停止充电失败')
                }
                
            }else {
                hideLoading()
                showModal('停止充电失败')
            }
        }, 5000);
        
    }


    function stopCharge() {
        showModal({
            content : '确定停止充电吗',
            showCancel : true,
            success : async ({cancel}) => {
                if(cancel) return
                setqueryOrderStatusCount(0)
                showLoading()
                const orderId = orderList[currentIndex].orderId
                const res = await stopChargeApi(orderId)
                if(res.success) {
                    queryStopOrderStatus(orderId)
                }else {
                    hideLoading()
                    showModal(res.msg)
                }
                
            }
        })
    }


    useReady(() => {
        setINIT(true)
        if(orderId) {
            Taro.setNavigationBarTitle({
                title : '充电详情'
            })
        }else {
            queryChargingOrder()
        }
        
    })

    useDidShow(() => {
        if(INIT) { //非第一次进来
            queryChargingOrder()
        }
    })


    return (
        <>
        <View className='vh-100 page-view'>
            <View id='a'></View>
            <Swiper className='swiper' onChange={e => setcurrentIndex(e.detail.current)}>
                {
                    orderList.map(order => {
                        return <>
                            <SwiperItem className='swiper-item'>
                                <View className='order-card'>
                                    <AtDivider content={strategyTypeIsTime(order.strategyType) ? '已充时长' : '已充电量'} fontSize='40' height='150' fontColor='#333333' lineColor='#f3f4f5' />
                                    {strategyTypeIsTime(order.strategyType)
                                    ? <ChargeQuEl type={order.strategyType} quantity={order.realTimeInfo ? order.realTimeInfo.consumeTime : 0}></ChargeQuEl>
                                    : <ChargeQuEl type={order.strategyType} quantity={order.realTimeInfo ? order.realTimeInfo.consumeEnergy : 0}></ChargeQuEl>
                                    }
                                    <View className='order-info'>
                                        <View>
                                            <Text className='f-32'>预付金额</Text>
                                            <Text className='pull-right f-32'>{order.chargeAmount}元</Text>
                                        </View>
                                        <View>
                                            <Text className='color-666' selectable={true}>设备编号</Text>
                                            <Text className='pull-right color-666'>{order.deviceId}</Text>
                                        </View>
                                        <View>
                                            <Text className='color-666'>插座编号</Text>
                                            <Text className='pull-right color-666'>#{order.portNo}号</Text>
                                        </View>
                                        <View>
                                            <Text className='color-666'>下单时间</Text>
                                            <Text className='pull-right color-666'>{order.createTime}</Text>
                                        </View>
                                    </View>
                                    <View className='m-t-30 text-right'><Text>订单号：</Text><Text className='color-primary' selectable={true}>{order.orderNo}</Text></View>
                                </View>
                            </SwiperItem>
                        </>
                    })
                }
            </Swiper>
            {!orderId && 
                <>
                {orderList.length > 1 &&
                    <View className='indicator m-t-40'>
                    {
                        orderList.map((order, index) => {
                            let className = 'dot'
                            if(currentIndex == index) {
                                className += ' active'
                            }
                            return <View className={className}></View>
                        })
                    }
                    </View>

                    }

                    <View className='text-center m-t-60'>共<Text className='color-primary f-36'> {orderList.length} </Text>个订单</View>
                </>
            }
            

            <View className='confirm-button p-l-r'>
                <View className='flex-align-items-center'>
                    <View className='flex-1'>
                        <Button hover-class='none' className='f-32' onClick={stopCharge}>停止充电</Button>
                    </View>
                    <View className='flex-1 m-l-40'>
                        <Button type='primary' hover-class='none' className='f-32' onClick={goAddCharge}>增加充电</Button>
                    </View>
                </View>
            </View>

        </View>

        {loadingData.showLoadingPage &&
            <XLoadingPage loading={!loadingData.loadErr}>
                <View className='text-center'>{loadingData.loadingErrMsg}</View>
            </XLoadingPage>
        }

        </>
    )
}